﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Mobileterminal.Common;
using Mobileterminal.Dtos;
using Mobileterminal.Forms.Yjb;
using Mobileterminal.Forms.Zyy;
using Newtonsoft.Json;
using Sunny.UI;

namespace Mobileterminal.Forms
{
    public partial class ConsumableMaterial : UIPage
    {
        public ConsumableMaterial()
        {
            InitializeComponent();
            ConfigureTreeView();
            ShowConsumn();
            LoadTreeDataAsync();
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            ConfigureTreeView();
            ShowConsumn();
            LoadTreeDataAsync();
        }

        private async Task ShowConsumn(string consumableCode = null, string consumableName = null)
        {
            // 构建动态查询参数
            var queryParams = new List<string>();
            if (!string.IsNullOrEmpty(consumableCode))
                queryParams.Add($"consumableCode={Uri.EscapeDataString(consumableCode)}");
            if (!string.IsNullOrEmpty(consumableName))
                queryParams.Add($"consumableName={Uri.EscapeDataString(consumableName)}");

            var url = "https://localhost:7224/api/Show/Showhc";
            if (queryParams.Count > 0)
                url += "?" + string.Join("&", queryParams);
            var json = await HttpClientHelper.ClientAsync("GET", url);
            var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Result<List<ConsumableMaterialDTO>>>(json);
            if (result.Code == 200)
            {
                result.Data = result.Data.OrderByDescending(x => x.ConsumableId).ToList();
                foreach (var item in result.Data)
                {
                    item.Statu = item.Status == false ? "停用" : "启用";
                }
                
                // 先清除所有列
                uiDataGridView1.Columns.Clear();
                
                // 设置数据源
                uiDataGridView1.DataSource = result.Data;
                
                // 添加操作列
                DataGridViewTextBoxColumn actionColumn = new DataGridViewTextBoxColumn();
                actionColumn.Name = "操作";
                actionColumn.HeaderText = "操作";
                actionColumn.ReadOnly = true;
                actionColumn.Width = 150;
                uiDataGridView1.Columns.Add(actionColumn);
                
                // 将操作列移到最后一列
                uiDataGridView1.Columns["操作"].DisplayIndex = uiDataGridView1.Columns.Count - 1;
                
                // 设置列宽
                foreach (DataGridViewColumn column in uiDataGridView1.Columns)
                {
                    if (column.Name != "操作")
                    {
                        column.Width = 100; // 设置默认列宽
                    }
                }
            }
        }

        /// <summary>
        /// 树形控件样式​
        /// </summary>
        private void ConfigureTreeView()
        {
            // 初始化图片列表
            var imageList = new ImageList
            {
                ImageSize = new Size(24, 24)
            };

            uiTreeView1.ImageList = imageList;
            uiTreeView1.ItemHeight = 32;
            uiTreeView1.ShowLines = true;
            uiTreeView1.LineColor = Color.Silver;
        }

        /// <summary>
        /// / 树形结构转换方法
        /// </summary>
        public static class TreeConverter
        {
            public static List<ConsumTypeTreeDTO> BuildTree(List<ConsumTypeTreeDTO> source)
            {
                var nodeMap = new Dictionary<int, ConsumTypeTreeDTO>();
                var rootNodes = new List<ConsumTypeTreeDTO>();

                // 第一遍：建立索引
                foreach (var node in source)
                {
                    nodeMap[node.value] = node;
                }

                // 第二遍：建立父子关系
                foreach (var node in source)
                {
                    if (node.parentId.HasValue && nodeMap.TryGetValue(node.parentId.Value, out var parent))
                    {
                        parent.children.Add(node);
                    }
                    else
                    {
                        // 没有parentId或父节点不存在时作为根节点
                        rootNodes.Add(node);
                    }
                }

                return rootNodes;
            }
        }

        /// <summary>
        /// 树状
        /// </summary>
        /// <returns></returns>
        private async Task LoadTreeDataAsync()
        {
            try
            {
                uiTreeView1.BeginUpdate();

                var url = "https://localhost:7224/api/Show/ShowTree";
                var json = await HttpClientHelper.ClientAsync("GET", url);
                Console.WriteLine($"获取到的 JSON 数据: {json}"); // 添加日志输出

                var result = JsonConvert.DeserializeObject<Result<List<ConsumTypeTreeDTO>>>(json);
                Console.WriteLine($"解析结果: {result?.Code}"); // 添加日志输出

                if (result?.Code == 200)
                {
                    // 添加虚拟根节点（根据业务需要）
                    var fullData = new List<ConsumTypeTreeDTO>
            {
                new ConsumTypeTreeDTO
                {
                    value = 0,
                    label = "全部器械分类",
                    children = TreeConverter.BuildTree(result.Data)
                }
            };

                    uiTreeView1.Nodes.Clear();
                    uiTreeView1.Nodes.AddRange(ConvertToSunnyNodes(fullData));
                    uiTreeView1.ExpandAll();
                }
            }
            catch (Exception ex)
            {
                // 处理异常，例如网络错误、JSON 解析错误等
                UIMessageTip.ShowError($"加载树形数据时出错: {ex.Message}");
                Console.WriteLine($"加载树形数据时出错: {ex.Message}"); // 添加日志输出
            }
            finally
            {
                uiTreeView1.EndUpdate();
            }
        }

        /// <summary>
        /// // SunnyUI树节点转换方法
        /// </summary>
        /// <param name="treeData"></param>
        /// <returns></returns>
        private TreeNode[] ConvertToSunnyNodes(List<ConsumTypeTreeDTO> treeData)
        {
            var nodes = new List<TreeNode>();

            foreach (var item in treeData)
            {
                var node = new TreeNode
                {
                    Text = item.label,
                    Tag = item.value, // 存储分类ID用于后续查询
                    ForeColor = Color.FromArgb(72, 72, 72), // 深灰色字体
                    //NodeStyle = UINodeStyle.CheckBox // 带复选框的节点样式
                };

                // 递归添加子节点
                if (item.children?.Count > 0)
                {
                    node.Nodes.AddRange(ConvertToSunnyNodes(item.children));
                }

                nodes.Add(node);
            }

            return nodes.ToArray();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private async void button1_Click_1(object sender, EventArgs e)
        {
            using (AddConsumableMaterial addConsumableMaterials = new AddConsumableMaterial())
            {
                if (addConsumableMaterials.ShowDialog() == DialogResult.OK)
                {
                    Refresh(); // 操作成功后刷新
                }
            }
        }

        //private void button2_Click(object sender, EventArgs e)
        //{

        //}

        //private void uiTextBox1_TextChanged(object sender, EventArgs e)
        //{

        //}

        private async void uiButton2_Click(object sender, EventArgs e)
        {

            // 获取输入条件
            string consumableCode = uiTextBox1.Text.Trim();
            string consumableName = uiTextBox2.Text.Trim();

            try
            {
                await ShowConsumn(consumableCode, consumableName);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询异常：{ex.Message}");
            }

        }


        private async void uiTextBox1_TextChanged(object sender, EventArgs e)
        {      // 获取输入条件
            string consumableCode = " ";
            string consumableName = " ";


            try
            {
                await ShowConsumn(consumableCode, consumableName);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询异常：{ex.Message}");
            }

        }

        private void uiButton4_Click(object sender, EventArgs e)
        {

        }
        private void uiDataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        #region 操作 修改
        /// <summary>
        /// 表格的重绘事件 DataGridViewCellPaintingEventArgs
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiDataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)//重绘"操作列",使其有三个按钮
        {
            //var a=e as DataGridViewCellPaintingEventArgs;

            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                //
                if (this.uiDataGridView1.Columns[e.ColumnIndex].HeaderText == "操作" && this.uiDataGridView1.Rows[e.RowIndex].Cells["ConsumableId"].Value != null)
                {
                    StringFormat sf = StringFormat.GenericDefault.Clone() as StringFormat;//设置重绘入单元格的字体样式
                    sf.FormatFlags = StringFormatFlags.DisplayFormatControl;
                    sf.Alignment = StringAlignment.Center;
                    sf.LineAlignment = StringAlignment.Center;
                    sf.Trimming = StringTrimming.EllipsisCharacter;

                    e.PaintBackground(e.CellBounds, false);//重绘边框

                    //设置要写入字体的大小
                    System.Drawing.Font myFont = new System.Drawing.Font("微软雅黑", 10F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(134)));

                    SizeF sizeMod = e.Graphics.MeasureString("编辑", myFont);
                    SizeF sizeDel = e.Graphics.MeasureString("删除", myFont);

                    float fMod = sizeMod.Width / (sizeDel.Width + sizeMod.Width);
                    float fDel = sizeDel.Width / (sizeDel.Width + sizeMod.Width);


                    //设置每个"按钮的边界"
                    RectangleF rectMod = new RectangleF(e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Width * fMod, e.CellBounds.Height);
                    //RectangleF rectMod = new RectangleF(rectPrint.Right, e.CellBounds.Top, e.CellBounds.Width * fMod, e.CellBounds.Height);
                    RectangleF rectDel = new RectangleF(rectMod.Right, e.CellBounds.Top, e.CellBounds.Width * fDel, e.CellBounds.Height);

                    Graphics grfx = CreateGraphics();
                    Color colorUse = Color.FromArgb(51, 136, 255);
                    Color colorPrint = Color.FromArgb(51, 136, 255);

                    e.Graphics.DrawString("编辑", myFont, new SolidBrush(colorUse), rectMod, sf);
                    e.Graphics.DrawString("删除", myFont, new SolidBrush(colorPrint), rectDel, sf); //绘制"按钮"
                    e.Handled = true;
                }
            }
        }
        /// <summary>
        /// 单元格点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void uiDataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
                {
                    if (this.uiDataGridView1.Columns[e.ColumnIndex].Name == "操作" && 
                        uiDataGridView1.Rows[e.RowIndex].Cells["ConsumableId"].Value != null)
                    {
                        int buttonWidth = this.uiDataGridView1.Columns[e.ColumnIndex].Width / 2;
                        
                        // 判断点击的是编辑还是删除按钮
                        if (e.Location.X < buttonWidth)
                        {
                            // 编辑按钮
                            var consumableId = this.uiDataGridView1.Rows[e.RowIndex].Cells["ConsumableId"].Value.ToString();
                            UpdateConsumableMaterial addshelf = new UpdateConsumableMaterial(consumableId);
                            addshelf.Show();
                        }
                        else
                        {
                            // 删除按钮
                            var consumableId = this.uiDataGridView1.Rows[e.RowIndex].Cells["ConsumableId"].Value.ToString();
                            var pdata = new { ConsumableId = consumableId };
                            HttpContent content = new StringContent(JsonConvert.SerializeObject(pdata), Encoding.UTF8, "application/json");
                            var hosn = HttpClientHelper.ClientAsync("put", "https://localhost:7286/api/Yjb/DelConsum", true, content).Result;
                            ConsumableMaterialDTO result = JsonConvert.DeserializeObject<ConsumableMaterialDTO>(hosn);
                            if (result != null)
                            {
                                MessageBox.Show("删除成功");
                                await ShowConsumn(); // 刷新数据
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"操作失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 在按钮上鼠标箭头变成小手样式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiDataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                if (this.uiDataGridView1.Columns[e.ColumnIndex].Name == "操作")
                {
                    this.Cursor = Cursors.Hand;
                }
                else
                {
                    this.Cursor = Cursors.Default;
                }
            }
        }





        #endregion

        private void ConsumableMaterial_Initialize(object sender, EventArgs e)
        {

        }

        private void uiTreeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {

        }
    }
}    